define(['butterfly/view', 'css!main/update.css', 'main/ModuleManager', 'main/ModuleManager-browser', 'main/util', 'spin', 'butterfly/notification'],
	function(View, CSS, Manager, ManagerBrowser, Util, Spin, Notification) {
	return View.extend({

		events: {
			"click .segmented-control a": 'changePanel',
			"click #updateBtn": "updateModule",
			'click #actionEdit': 'edit',
			"click #removeBtn": 'uninstallModule'
		},

		onShow: function() {
			var is_cordova = (typeof cordova != "undefined")
			var manager = this.manager = is_cordova ? new Manager() :new ManagerBrowser();
			var username = Util.loadData('username');
			manager.getPrivellege(username, function(privellege) {
        manager.privellege = privellege.priviliges;
      });
			this.refreshInstalledPanel();
		},

		changePanel: function(e) {
			this.$('.segmented-control a').removeClass("active");
			$(e.currentTarget).toggleClass("active");
			var panelId = $(e.currentTarget).data('panel');
			this.$(".module-panel").css("display","none");
			this.$("#" + panelId).css("display","block");
			switch(panelId) {
				case 'panel-installed':
					this.refreshInstalledPanel();
				break;
				case 'panel-update':
					this.refreshCanUpdatePanel();
				break;
			}
		},

		uninstallModule: function(event) {
			var _this = this;
			var identifier = $(event.currentTarget).data("identifier");
			this.manager.deleteModel(identifier, function() {
				_this.$(".module-list li[data-identifier='" + identifier + "']").remove();
				var installedModules = Util.loadData('installedModules');
				installedModules = _.reject(installedModules, function(module) {
					return module.identifier == identifier;
				});
				Util.saveData('installedModules', installedModules);
			});
		},

		edit: function() {
			if(this.$('#actionEdit').text() == '编辑') {
				this.$('#actionEdit').text('取消');
				this.$(".module-list li #removeBtn").css('display', 'block');
			} else {
				this.$('#actionEdit').text('编辑');
				this.$(".module-list li #removeBtn").css('display', 'none');
			}
		},

		updateModuleBoard: function(installed) {
			Util.saveData('installedModules', installed);
		},

		// 已绑定事件：点击更新面板触发
		refreshCanUpdatePanel: function() {
			if(this.isLoadingUpdate) return;
			var html = this.$("#module-update-template").html();
			var tmpl = _.template(html);
			var _this = this;
			var spin = new Spin().spin(this.el);
			this.isLoadingUpdate = true;
			this.manager.checkUpdate(function(data) {
				_this.isLoadingUpdate = false;
				spin.stop();
				console.log(data);
				_this.canUpdateModules = data;
				_this.$("#panel-update .module-list").html("");
				// modify by hyw 添加icon显示的方法
				var appIcon = Util.loadData('appIcon') || {}; // <identifier, icon>
				_.each(data, function(module) {

					if(!_this.manager.isAllow(module.identifier, 'GET'))return;

					appIcon[module.identifier] = module.icon; // 添加图片pair

					module.description = "无描述";
					var icon = module.icon;
					module.icon = icon.length == 18 ? icon : "default"
					var cell = tmpl(module);
					_this.$("#panel-update .module-list").append(cell);
				});
				Util.saveData('appIcon', appIcon);
			}, function(err) {
				console.log(err);
			});
		},

		// 已绑定事件：点击安装模块面板触发
		refreshInstalledPanel: function() {
			if(this.isLoadingInstalled) return;
			var html = this.$("#module-installed-template").html();
			var tmpl = _.template(html);
			var _this = this;
			var installedModules = Util.loadData('installedModules');
			render(installedModules);
			var spin = new Spin().spin(this.el);
			this.isLoadingInstalled = true;
			this.manager.getLocalModulesInfo(function(data) {
				_this.isLoadingInstalled = false;
				spin.stop();
				Util.saveData('installedModules', data);
				render(data);
			}, function(err) {
				console.log(err)
			});

			function render(data) {
				_this.$("#panel-installed .module-list").html("");
				var appIcon = Util.loadData('appIcon');
				_.each(data, function(module) {
					if(!module.identifier || !module.build) return;
					module.description = "无描述"
					// module.icon = module.icon || "default"
					module.icon = appIcon && appIcon[module.identifier] || "default"
					var cell = tmpl(module);
					_this.$("#panel-installed .module-list").append(cell);
				})
			}
		},

		updateModule: function(e) {
			var bundle = $(e.currentTarget).data('bundle'); // data-bundle
			var module = _.find(this.canUpdateModules, function(module) {
				return module.bundle == bundle
			})

			if(!this.manager.isAllow(module.identifier, 'GET')) {
				return new Notification({
					message: '当前模块无下载权限',
					type: 'error'
				}).show();
			}

			$(e.currentTarget).css('pointer-events','none');
			$(e.currentTarget).text('下载中');
			this.manager.downloadModules([module], function(state) {
				if(state === 'success') {
					$(e.currentTarget).parent().remove();
				}
			});
		}

	})
})
